﻿using Microsoft.AspNet.SignalR;
using SignalRWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;

namespace SignalRWeb.Hubs
{
    public class Broadcaster 
    {
        private readonly static Lazy<Broadcaster> _instance = new Lazy<Broadcaster>(()=> new Broadcaster());
        private readonly TimeSpan fileHubInterval = TimeSpan.FromMilliseconds(20);
        private IHubContext context;
        private Timer loopUpdate;
        private ShapeModel _model;
        private bool modelUpdate;

        public Broadcaster()
        {
            this.context = GlobalHost.ConnectionManager.GetHubContext<FileHub>();
            this._model = new ShapeModel();
            this.modelUpdate = false;
            this.loopUpdate = new Timer(
                ChangeShape,
                null,
                fileHubInterval,
                fileHubInterval
                );
        }

        public void ChangeShape(object state)
        {
            if (modelUpdate)
            {
                context.Clients.AllExcept(_model.LastUpdatedBy).UpdateShape(_model);
                modelUpdate = false;
            }
        }

        public void UpdateShape(ShapeModel model)
        {
            this._model = model;
            modelUpdate = true;
        }

        public static Broadcaster Instance
        {
            get { return _instance.Value; }
        }
    }

    public class FileHub : Hub
    {
        private Broadcaster _broadcaster;
        public FileHub() : this(Broadcaster.Instance)
        {

        }
        public FileHub(Broadcaster broadcaster) 
        {
            _broadcaster = broadcaster;
        }

        public void UpdateModel(ShapeModel clientModel)
        {
            clientModel.LastUpdatedBy = Context.ConnectionId;
            // Update the shape model within our broadcaster
            _broadcaster.UpdateShape(clientModel);
        }
    }
}